package com.chen.config;

import com.chen.bean.enums.ResultCode;
import com.chen.bean.result.Result;
import com.chen.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public Result<?> doBusinessException(BusinessException e, HttpServletRequest request){
        log.error(String.format("error message:[%s], request url:[%s]", e.getMessage(), request.getRequestURL()), e);
        return Result.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(WxErrorException.class)
    public Result<?> doWxErrorException(WxErrorException e, HttpServletRequest request){
        log.error(String.format("error message:[%s], request url:[%s]", e.getMessage(), request.getRequestURL()), e);
        return Result.fail(ResultCode.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class, HandlerMethodValidationException.class, ConstraintViolationException.class})
    public Result<?> handleValidationExceptions(Exception ex) {
        return Result.fail(ResultCode.ERROR_PARAMS.getCode(),ex.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public Result<?> doException(Exception e, HttpServletRequest request){
        log.error(String.format("error message:[%s], request url:[%s]", e.getMessage(), request.getRequestURL()), e);
        return Result.fail(ResultCode.INTERNAL_SERVER_ERROR);
    }

}
